"use client";

import { type ReactNode, createContext, useRef, useContext } from "react";
import { useStoreWithEqualityFn } from "zustand/traditional";
import {
  createPersonalDetailStore,
  PersonalDetailStore,
} from "../stores/personal-detail-store";

export type StoreApi = ReturnType<typeof createPersonalDetailStore>;

export const StoreContext = createContext<StoreApi | undefined>(undefined);

export interface PersonalDetailStoreProviderProps {
  children: ReactNode;
  personalDetails: PersonalDetails;
}

export const PersonalDetailStoreProvider = ({
  children,
  personalDetails,
}: PersonalDetailStoreProviderProps) => {
  const storeRef = useRef<StoreApi>();
  if (!storeRef.current) {
    storeRef.current = createPersonalDetailStore({ ...personalDetails });
  }

  return (
    <StoreContext.Provider value={storeRef.current}>
      {children}
    </StoreContext.Provider>
  );
};

export const usePersonalDetailStore = <T,>(
  selector?: (store: PersonalDetailStore) => T,
  equalityFn?: (a: T, b: T) => boolean
): T => {
  const personalDetailStoreContext = useContext(StoreContext);

  if (!personalDetailStoreContext) {
    throw new Error(`useCounterStore must be used within CounterStoreProvider`);
  }

  return useStoreWithEqualityFn(
    personalDetailStoreContext,
    selector,
    equalityFn
  );
};
